package com.husd.leetcode.tree;

import com.husd.leetcode.entry.TreeNode;

/**
 * @author hushengdong
 */
public class TreeUtils {

    public static void print(TreeNode head) {

        //打印二叉树
        if (head == null) {
            return;
        }
        int depth = depth(head);
        int arrayHeight = depth * 2 - 1;
        int arrayWidth = (2 << (depth - 2)) * 3 + 1;
        String[][] res = new String[arrayHeight][arrayWidth];
        // 对数组进行初始化，默认为一个空格
        for (int i = 0; i < arrayHeight; i++) {
            for (int j = 0; j < arrayWidth; j++) {
                res[i][j] = " ";
            }
        }

        writeArray(head, 0, arrayWidth / 2, res, depth);

        // 此时，已经将所有需要显示的元素储存到了中，将其拼接并打印即可
        for (String[] line : res) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < line.length; i++) {
                sb.append(line[i]);
                if (line[i].length() > 1 && i <= line.length - 1) {
                    i += line[i].length() > 4 ? 2 : line[i].length() - 1;
                }
            }
            System.out.println(sb.toString());
        }
    }

    private static void writeArray(TreeNode currNode, int rowIndex, int columnIndex, String[][] res, int treeDepth) {
        // 保证输入的树不为空
        if (currNode == null) return;
        // 先将当前节点保存到二维数组中
        res[rowIndex][columnIndex] = String.valueOf(currNode.value2String());

        // 计算当前位于树的第几层
        int currLevel = ((rowIndex + 1) / 2);
        // 若到了最后一层，则返回
        if (currLevel == treeDepth) return;
        // 计算当前行到下一行，每个元素之间的间隔（下一行的列索引与当前元素的列索引之间的间隔）
        int gap = treeDepth - currLevel - 1;

        // 对左儿子进行判断，若有左儿子，则记录相应的"/"与左儿子的值
        if (currNode.left != null) {
            res[rowIndex + 1][columnIndex - gap] = "/";
            writeArray(currNode.left, rowIndex + 2, columnIndex - gap * 2, res, treeDepth);
        }

        // 对右儿子进行判断，若有右儿子，则记录相应的"\"与右儿子的值
        if (currNode.right != null) {
            res[rowIndex + 1][columnIndex + gap] = "\\";
            writeArray(currNode.right, rowIndex + 2, columnIndex + gap * 2, res, treeDepth);
        }
    }

    private static int depth(TreeNode node) {

        return node == null ? 0 : (1 + Math.max(depth(node.left), depth(node.right)));
    }

    public static boolean red(TreeNode treeNode) {

        return treeNode != null && treeNode.isRed();
    }

    public static boolean black(TreeNode treeNode) {

        return !red(treeNode);
    }
}
